<template>
    <view>
        <view class="box">
            <!--回收员下单页面-->
            <view class="userphone" v-if="isHsType != 1">
                <view>
                    <text>联系人</text>
                    <input type="text" v-model="data.phone_name" disabled="true" />
                </view>
                <view>
                    <text>手机号</text>
                    <input type="number" v-model="data.mobile" disabled="true" />
                </view>
            </view>
            <view class="useraddress" v-if="isHsType != 1">
                <view>
                    <text>定位地址</text>
                    <span style="width: 400rpx;text-overflow:ellipsis;overflow:hidden;white-space:nowrap;">{{ data.location_address || '请定位地址' }}</span>
                    <image style="margin-top: 0;" src="../../static/img/myhome/icon-dingwei@3x.png" mode=""></image>
                </view>
                <view>
                    <text>详细地址</text>
                    <input type="text" v-model="data.recycling_address" disabled="true" />
                </view>
            </view>
            <view class="usertime" v-if="isHsType != 1">
                <view>
                    <text>预约时间</text>
                    <!-- 日期 -->
                    <picker mode="date" :value="date" :start="startDate" :end="endDate" @change="bindDateChange">
                        {{ date }}
                        <u-icon name="arrow-down-fill" color="#999999" size="20" style="margin-left: 30rpx;"></u-icon>
                    </picker>
                    <!-- 日期 -->
                </view>
                <view>
                    <button @click="selectBu(item)" v-for="item in buttontiem" :key="item" :class="{ selectButoom: buttonseletct == item }">
                        <i>{{ item }}</i>
                    </button>
                </view>
            </view>
            <view class="userphone" v-if="isHsType == 1"
                    style="height: unset; display: flex; align-items: center; padding: 10rpx;">
                <view style="border-bottom: none;" @click="selectShow = true">
                    <text>用户</text>
                    <text :style="{ paddingLeft: '30rpx', color: selectText ? '#000' : '#CCCCCC', 'max-width':'400rpx', 'overflow': 'hidden'}">{{ selectText || '请选择用户' }}</text>
                    <u-icon name="arrow-down" size="24" color="#cccccc" style="margin-left: 30rpx;"></u-icon>
                </view>
                <u-button type="primary" @click="isShowMobile=true">手机查询</u-button>
            </view>
            <view class="textg"><text>已添加物品</text></view>
            <view class="usergoods">
                <addgood v-for="(item, index) in data.wp" :index="index" :wp="item" :key="item" @wpDelete="wpDelete" @showEdit="showEdit(item, index)"></addgood>
            </view>
            <view class="add_product">
                <button @click="isShowadd_pro">
                    <image src="../../static/img/myhome/add@3x.png"></image>
                    <text>继续添加商品</text>
                </button>
            </view>
        </view>

        <!-- 展示继续添加商品弹窗 s -->
        <u-popup v-model="isShow" mode="bottom"><addprods :prevWeight="aWeight" @myEven="change" @closewin="colse" ref="popupAdd"></addprods></u-popup>

        <!-- 展示编辑商品弹窗 s -->
        <u-popup v-model="isShowEdit" mode="bottom"><editgood @myEven="changeEdit" @closewin="colseEdit" ref="popupEdit"></editgood></u-popup>

        <u-popup v-model="isShowMobile" mode="bottom"><mobilequery @myEven="changeMobile" :user-list="vuserList" @closewin="colseMobile" ref="popupMobile"></mobilequery></u-popup>

        <!-- 总计金额 -->
        <view class="footer">
            <button type="default" v-if="isHsType == 1" @click="hang()">挂起</button>
            <view class="sub">
                <text>累计金额:</text>
                <span>{{ amount || 0 }}</span>
                <text>元</text>
                <button @click="post"><i>提交</i></button>
            </view>
        </view>

        <u-select v-model="selectShow" mode="single-column" label-name="nickname" value-name="id" :list="vuserList" @confirm="selectConfirm"></u-select>
        <u-popup v-model="popupShow" mode="center" border-radius="20">
            <view style="padding: 50rpx;width: 500rpx;">
                <view style="font-size: 35rpx;font-weight: bold;text-align: center;">输入密码</view>
                <view style="display: flex;font-size: 30rpx;padding: 50rpx 0;">
                    <!-- <view style="width: 150rpx;text-align: right;">密码：</view> -->
                    <view style="width: 100%;">
                        <input type="number" v-model="password" maxlength="6" placeholder="请输入六位密码" password style="border-bottom: 1rpx solid #999999;"/>
                    </view>
                </view>
                <view style="display: flex;justify-content: space-around;">
                    <u-button type="success" size="mini"  @click="sendPassword(1)" :disabled="disabledStatus" v-if="service_init.pay_type.indexOf('1') > -1">现金支付</u-button>
                    <u-button type="success" size="mini" @click="sendPassword(2)" :disabled="disabledStatus" v-if="service_init.pay_type.indexOf('2') > -1">余额支付</u-button>
<!--                     <button @click="sendPassword(1)" class="pay_btn" :disabled="disabledStatus" v-if="service_init.pay_type.indexOf('1') > -1">现金支付</button>
                    <button @click="sendPassword(2)"  class="pay_btn":disabled="disabledStatus" v-if="service_init.pay_type.indexOf('2') > -1">余额支付</button> -->
                </view>
            </view>
        </u-popup>
    </view>
</template>

<script>
import Addgood from '../scan_user/Addgood1.vue';
import addprods from '../scan_user/add_product1.vue';
import editgood from './editgood1.vue';
import mobilequery from '../scan_user/mobile_query1.vue';

export default {
    components: {
        Addgood,
        addprods,
        editgood,
        mobilequery
    },
    data() {
        const currentDate = this.getDate({
            format: true
        });
        return {
            userInfo: null,
            date: currentDate,
            isShow: false,
            isShowEdit: false,
            isShowMobile: false,
            data: {},
            buttonseletct: '',
            buttontiem: ['08:00~10:00', '10:00~12:00', '14:00~16:00', '16:00~18:00'],
            vuserList: [],
            isHsType: 1,
            selectShow: false,
            selectText: null,
            aWeight:'',
            password: '',
            popupShow: false,
            service_init:{
                pay_type:[]
            }
        };
    },
    onLoad(options) {
        let is_hs = uni.getStorageSync('is_hs');
        console.log('========1====' + !this.$u.test.isEmpty(options.data))
        if (!this.$u.test.isEmpty(options.data)) {
            this.data = JSON.parse(options.data);
            let times = this.data.pickup_time_area.split(' ');
            this.date = times[0];
            this.buttonseletct = times[1];
            console.log('========2====' + is_hs)
            if (is_hs == 3) {
                // this.aWeight = this.data.wp[this.data.wp.length - 1].a_weigh
                this.selectText = this.data.nickname;
                this.data.vuid = this.data.uid;
                this.isHsType = 1;
                this._getVuser();
                uni.setNavigationBarTitle({
                    title: '总仓编辑订单'
                });
            }else if (is_hs == 5) {
                // this.aWeight = this.data.wp[this.data.wp.length - 1].a_weigh
                console.log(this.data)
                this.selectText = this.data.nickname;
                this.data.vuid = this.data.uid;
                this.isHsType = 1;
                this._getVuser();
                uni.setNavigationBarTitle({
                    title: '分站编辑订单'
                });
            }
        } else {
            console.log('========3====' + is_hs)
            if (is_hs == 3) {
                this.data = {
                    mobile: '',
                    phone_name: '',
                    location_address: '',
                    recycling_address: '',
                    pickup_time: '',
                    pickup_time_area: '',
                    longitude: '',
                    latitude: '',
                    wp: [],
                    is_virtual: 1,
                    vuid: null
                };
                this.isHsType = 1;
                this._getVuser();
                uni.setNavigationBarTitle({
                    title: '总仓下单'
                });
            }else if (is_hs == 5) {
                this.data = {
                    mobile: '',
                    phone_name: '',
                    location_address: '',
                    recycling_address: '',
                    pickup_time: '',
                    pickup_time_area: '',
                    longitude: '',
                    latitude: '',
                    wp: [],
                    is_virtual: 2,
                    vuid: null
                };
                this.isHsType = 1;
                this._getVuser();
                uni.setNavigationBarTitle({
                    title: '分站下单'
                });
            }
        }
        this._getInfo();
        this._getServiceInit()
        
    },
    computed: {
        startDate() {
            return this.getDate('start');
        },
        endDate() {
            return this.getDate('end');
        },
        // 计算累计金额
        amount() {
            let total = 0;
            if (this.$u.test.isEmpty(this.data.wp)) {
                return;
            }
            this.data.wp.forEach((item, index) => {
                if (item.total_price > 0) {
                    total += Number(item.total_price);
                }
            });

            return total.toFixed(2);
        }
    },
    methods: {
        _getServiceInit(){
            this.$u.api.getServiceInit().then(res => {
                this.service_init = res
                uni.setStorageSync('service_init',res)
            })
        },
        // 用户信息api
        _getInfo() {
            this.$u.api.getInfo().then(res => {
                this.userInfo = res;
                uni.setStorageSync('is_hs', res.is_hs);
                this.$store.commit('setUserInfo', res)
                uni.setStorageSync('userInfo', res);
                this.$store.commit('setIsUserEdit', 0);
            }).catch(e => {})
        },
        selectConfirm(e) {
            console.log("-----selectConfirm-----");
            this.selectText = e[0].label;
            this.data.vuid = e[0].value;
        },
        selectBu(item) {
            this.buttonseletct = item;
        },
        hang(){
            if (!this.data.re_id) this.data.re_id = this.$store.state.userInfo.id;
            var that = this
            if (this.$u.test.isEmpty(this.data.vuid)) {
                uni.showToast({
                    title: '请选择用户',
                    duration: 1000,
                    icon: 'none'
                });
                return;
            } else if (this.$u.test.isEmpty(this.data.wp)) {
                uni.showToast({
                    title: '请添加至少一项物品',
                    duration: 1000,
                    icon: 'none'
                });
                return;
            } else {
                uni.showModal({
                    title: '提示',
                    content: '是否暂时挂起',
                    showCancel: true,
                    success: function (res) {
                        if (res.confirm) {
                            that._postHangAdd(that.data);
                        } else if (res.cancel) {}
                    }
                });
            }
        },
        _postHangAdd(data){
            uni.showLoading({
                title: '加载中'
            });
            this.$u.api
                .postHangScan(data)
                .then(res => {
                    uni.hideLoading();
                    uni.showToast({
                        title:'挂起成功',
                        icon:'none'
                    })
                    setTimeout(function(){
                        uni.navigateBack({
                            delta: 1
                        });
                    },1500)
                })
                .catch(err => {
                    uni.hideLoading();
                    uni.showToast({
                        title: err.msg,
                        duration: 1000
                    });
                });
        },
        post() {
            var that = this;
            if (that.isHsType == 1) {
                if (that.$u.test.isEmpty(that.data.vuid)) {
                    uni.showToast({
                        title: '请选择用户',
                        duration: 1000,
                        icon: 'none'
                    });
                    return;
                } else if (that.$u.test.isEmpty(that.data.wp)) {
                    uni.showToast({
                        title: '请添加至少一项物品',
                        duration: 1000,
                        icon: 'none'
                    });
                    return;
                } else {
                    //20221123在付款前确认回皮重量
                    uni.showModal({
                        title: '提示',
                        content: '是否已经填写回皮重量？',
                        showCancel: true,
                        cancelText: '去填写',
                        confirmText: '付款',
                        success: function (res) {
                            if (res.confirm) {
                                console.log('用户点击确定');
                                that.popupShow = true;
                            } else if (res.cancel) {
                                console.log('用户点击取消');
                            }
                        }
                    });
                    
                    // this.selectPayType();
                    // this._postRecoverAdd(this.data);
                }
            } else {
                that._postRecoverEdit();
            }
        },
        selectPayType() {
            var that = this;
            uni.showModal({
                showCancel: true,
                title: '请选择支付方式',
                content: '支付金额：￥'+this.amount,
                cancelText: '余额支付',
                confirmText: '现金支付',
                success: (res) => {
                    if (res.confirm) {
                        that._postRecoverAdd(that.data);
                    } else if (res.cancel) {
                        that.popupShow = true;
                        // this._postUserOrderPay(ids, 1);
                    }
                }
            });
        },
        /*验证支付密码*/
        sendPassword(type) {
            var that = this;
            if(that.$u.test.isEmpty(that.password)) {
                uni.showToast({
                    title: '请输入密码',
                    duration: 1000,
                    icon: 'none',
                });
                return false;
            }
            that.$u.api.checkUserPayPassword({ 'password': that.password }).then(res=>{
                if(type == 2){
                    if ( parseFloat(that.amount) > parseFloat(that.userInfo.balance) ) {
                        uni.showToast({
                            title: '余额不足',
                            duration: 1000,
                            icon: 'none'
                        });
                        that.popupShow = false;
                        that.password = '';
                        return false;
                    }
                }

                that.data.send_type = type
                that._postRecoverAdd(that.data);
            }).catch(err=>{
                uni.showToast({
                    title: err.msg,
                    duration: 1000,
                    icon: 'none'
                });
            })
        },
        _postRecoverEdit() {
            this.$u.api.postRecoverEdit(this.data).then(res => {
                uni.showModal({
                    title: '提示',
                    content: '操作成功',
                    showCancel: false,
                    success: res => {
                        if (res.confirm) {
                            uni.navigateBack({
                                delta: 1
                            });
                            this.$store.commit('setEditOrder', 1);
                        } else if (res.cancel) {
                        }
                    }
                });
            });
        },
        _postRecoverAdd(data) {
            uni.showLoading({
                title: '加载中'
            });
            this.$u.api
                .postRecoverAdd(data)
                .then(res => {
                    uni.hideLoading();
                    this._postComplete(res.order_id,data.send_type);
                })
                .catch(err => {
                    uni.hideLoading();
                    uni.showToast({
                        title: err.msg,
                        duration: 1000
                    });
                });
        },
        _postComplete(id) {
            uni.showLoading({
                title: '加载中'
            });
            this.$u.api
                .postComplete({
                    id: id,
                    send_type:send_type
                })
                .then(res => {
                    uni.hideLoading();
                    // uni.showToast({
                    //     title: '订单完成',
                    //     duration: 1000
                    // });
                    uni.showModal({
                        title: '提示',
                        content: '下单成功',
                        showCancel: false,
                        success: function(res) {
                            if (res.confirm) {
                                uni.navigateBack({
                                    delta: 1
                                });
                            }
                        }
                    });
                })
                .catch(err => {
                    uni.hideLoading();
                    uni.showToast({
                        title: err.msg,
                        duration: 2000,
                        icon: 'none'
                    });
                });
        },
        bindDateChange: function(e) {
            this.date = e.target.value;
        },
        getDate(type) {
            const date = new Date();
            let year = date.getFullYear();
            let month = date.getMonth() + 1;
            let day = date.getDate();

            if (type === 'start') {
                year = year - 60;
            } else if (type === 'end') {
                year = year + 2;
            }
            month = month > 9 ? month : '0' + month;
            day = day > 9 ? day : '0' + day;
            return `${year}-${month}-${day}`;
        },
        // 日期 e
        // 弹窗
        isShowadd_pro() {
            this.isShow = true;
            if (this.isHsType == 1) {
                this.$refs.popupAdd.handPriceDisabled();
                this.$refs.popupAdd.prevWeight(this.aWeight);
            }
        },
        // 将子组件的数据 push 进 数组中
        change(options) {
            this.aWeight = options.a_weigh
            this.data.wp.push(options);
            this.isShow = false;
        },
        colse() {
            this.isShow = false;
        },

        showEdit(item, index) {
            if (this.isHsType == 1) {
                this.$refs.popupEdit.handPriceDisabled();
            }
            let isGetWeight = 1;    //是否获取重量，由于editgood.vue是被调用的包装元素，原来的并不传isGetWeight参数
            this.$refs.popupEdit.cre(item, index, isGetWeight);
            this.isShowEdit = true;
        },
        wpDelete(index) {
            this.$u.api.postRecoverDel({ id: this.data.wp[index].id });
            this.data.wp.splice(index, 1);
            this.aWeight = this.data.wp[this.data.wp.length - 1].a_weigh
        },
        // 将子组件的数据 push 进 数组中
        changeEdit(params) {
            //console.log("----------------changeEdit");
            //console.log(params.wp);
            //console.log(params.index);
            let index = params.index;
            let item = params.wp;
            //计算过磅前后重数，价线
            //console.log("----------------a_weigh");
            //console.log(item.a_weigh);
            //console.log("----------------b_weigh");
            //console.log(item.b_weigh);
            let aWeigh = Number(item.a_weigh) ? Number(item.a_weigh) : 0;
            let bWeigh = Number(item.b_weigh) ? Number(item.b_weigh) : 0;
            let rWeigh = Number(item.r_weigh) ? Number(item.r_weigh) : 0;
            //console.log(aWeigh);
            //console.log(bWeigh);
            if ( bWeigh > aWeigh ) {
                let tWeight = bWeigh - aWeigh - rWeigh;
                item.nums = tWeight;
                //item.weight = tWeight;
                item.total_price = item.nums * item.unit_price;
                item.total_price = item.total_price.toFixed(2);
            }
            //如果有多种货物，就把上一次卸货后的重量赋给下一个货物的过磅前重量
            if ( (aWeigh > 0) && (this.data.wp.length - index > 1) ) {
                this.data.wp[index+1].b_weigh = item.a_weigh;
            }
            
            this.data.wp[index] = item;
            this.isShowEdit = false;
            //console.log("---------this.data.wp---------");
            //console.log(this.data.wp);
        },
        colseEdit() {
            this.isShowEdit = false;
        },
        colseMobile() {
            this.isShowMobile = false;
        },
        changeMobile(item,index){            
            this.selectText = item.nickname;
            this.data.vuid = item.id;
            this.isShowMobile = false
        },
        _getVuser() {
            this.$u.api.getVuser().then(res => {
                this.vuserList = res;
            });
        }
    }
};
</script>

<style lang="scss" scoped>
    .pay_btn{
        background-color: #18B566;color: #FFFFFF; height: 75rpx;line-height: 75rpx;
    }
.cover_view {
    height: 300rpx;
    background-color: pink;
}

.box {
    padding: 30rpx;
    // background-color: #eee;
    // min-height: 1500rpx;
}

.textg {
    font-size: 32rpx;
    line-height: 38rpx;
    color: #2d3945;
    margin: 60rpx 0 30rpx 30rpx;
}

span {
    font-size: 28rpx;
    line-height: 48rpx;
    color: #666666;
    margin-left: 30rpx;
}

.userphone {
    background-color: #ffffff;
    border-radius: 20rpx;
    padding-left: 30rpx;
    line-height: 98rpx;
    margin-bottom: 30rpx;

    button {
        background-color: #2b85e4;
        color: #ffffff;
        transform: scale(0.8);
    }

    view:nth-child(1) {
        border-bottom: 1px solid #eeeeee;
        flex-grow: 1;
    }

    view {
        display: flex;
        align-items: center;

        input {
            padding-left: 30rpx;
        }
    }
}

.useraddress {
    height: 196rpx;
    background-color: #ffffff;
    border-radius: 20rpx;
    padding: 0 30rpx;
    line-height: 98rpx;
    margin-bottom: 30rpx;

    view:nth-child(1) {
        border-bottom: 1px solid #eeeeee;
    }

    view {
        display: flex;
        align-items: center;
        input {
            padding-left: 30rpx;
        }
    }

    image {
        float: right;
        margin-top: 30rpx;
        width: 50rpx;
        height: 50rpx;
    }
}

.usertime {
    height: 308rpx;
    background-color: #ffffff;
    border-radius: 20rpx;
    padding: 0 30rpx;
    line-height: 98rpx;
    margin-bottom: 30rpx;

    picker {
        font-size: 28rpx;
        color: #666666;
        text-align: left;
        margin-left: 30rpx;
        flex: 1;
    }

    view:nth-child(1) {
        border-bottom: 1px solid #eeeeee;
        display: flex;
    }

    view:nth-child(2) {
        margin-top: 30rpx;
        display: flex;
        flex-wrap: wrap;
    }

    button {
        width: 190rpx;
        height: 70rpx;
        border-radius: 35rpx;
        background-color: #ffffff;
        border: solid 2rpx #f2f2f2;
        margin: 0 10rpx 10rpx 0;
    }

    i {
        font-size: 24rpx;
        line-height: 70rpx;
        color: #999999;
    }

    .selectButoom {
        background-color: #1bc078;
        // color: #ffffff;

        i {
            color: #ffffff;
        }
    }
}

.add_product {
    margin-bottom: 10vh;

    button {
        width: 570rpx;
        height: 98rpx;
        line-height: 98rpx;
        background-color: #ffffff;
        border-radius: 49rpx;
    }

    text {
        font-size: 28rpx;
        color: #1bc078;
    }

    image {
        margin-right: 20rpx;
        width: 24rpx;
        height: 24rpx;
    }
}

.footer {
    position: fixed;
    bottom: 0;
    left: 0;
    width: 100%;
    padding: 10rpx 30rpx;
    background-color: #ffffff;
    padding-bottom: env(safe-area-inset-bottom);
    display: flex;
    flex-direction: column;

    text {
        font-size: 32rpx;
        color: #191919;
    }

    span {
        font-size: 32rpx;
        color: #ff4200;
        margin: 0 28rpx;
    }

    > button {
        position: absolute;
        left: 2%;
        top: -100%;
        border-radius: 999rpx;
        background-color: #f0ad4e;
        color: #fff;
        padding: 20rpx 30rpx;
    }

    .sub {
        display: flex;
        justify-content: space-around;
        align-items: center;
        margin-top: 5rpx;

        button {
            width: 262rpx;
            height: 78rpx;
            background-color: #1bc078;
            border-radius: 39rpx;
            margin: 0;

            i {
                font-size: 32rpx;
                color: #ffffff;
            }
        }
    }
}

.showeditgood {
    height: 100%;
    position: fixed;
    left: 0;
    right: 0;
    top: 0;
    z-index: 998;
}
</style>
